<template>
  <div class="box myBox">
    <van-nav-bar
      title="我的"
      right-text="设置"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push('/setting')"
    />
    <van-uploader :after-read="readOK">
      <van-image
        fit="contain"
        :src="userMsg.avatar"
      />
    </van-uploader>
    <p>用户名：{{userMsg.userName}}</p>
    <p>昵称：{{userMsg.nickName}}</p>
    <van-cell-group>
      <van-cell title="我的订单" is-link />
      <van-cell title="我的购物车" is-link />
      <van-cell title="我的收藏" is-link />
      <van-cell title="我的地址" is-link />
      <van-cell title="设置" is-link @click="$router.push('/setting')" />
    </van-cell-group>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Uploader, Image as VanImage, Cell, CellGroup } from 'vant'
import { getUser, setAvatar } from '@/request/index.js'

Vue.use(NavBar)
Vue.use(Uploader)
Vue.use(VanImage)
Vue.use(Cell)
Vue.use(CellGroup)

export default {
  beforeRouteEnter (to, from, next) {
    if (localStorage.getItem('isLogin') === 'ok') {
      next()
    } else {
      next('/login?to=my')
    }
  },
  data () {
    return {
      userMsg: {}
    }
  },
  mounted () {
    getUser().then(data => {
      // console.log(data.data)
      this.userMsg = {
        avatar: 'https://cas.1000phone.net/cas/images/login/logo.png',
        nickName: '临时用户',
        ...data.data.data
      }
    })
  },
  methods: {
    readOK (a) {
      setAvatar({
        avatar: a.content
      }).then(data => {
        // console.log(data.data)
        this.userMsg.avatar = a.content
      })
    }
  }
}
</script>

<style lang="scss">
.myBox{
  .van-uploader{
    margin: 0.2rem auto;
    .van-image{
      width: 1rem;
      height: 1rem;
      background: red;
    }
  }
  p{
    text-align: center;
  }
}
</style>
